/*
 * buttons.c
 *
 *  Created on: Nov 12, 2013
 *      Author: Ahmed
 */

#include "stm32f10x.h"
#include "buttons.h"

NVIC_InitTypeDef   	NVIC_InitStructure;
GPIO_InitTypeDef 	GPIO_InitStructure;

void Buttons_Config(void)
{
  /* Enable GPIOB clock */
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
  /* Configure PB0-PB3 pin as input floating */
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12 | GPIO_Pin_13 | GPIO_Pin_14 | GPIO_Pin_15;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  /* Enable AFIO clock */
   RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);

   /* Connect EXTI12-15 Line to PB.12-15 pin */
   GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource12);
   GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource13);
   GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource14);
   GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource15);


  /* Configure EXTI12-15 line initially for active low push button detection */
   configure_EXTI(EXTI_Line12 | EXTI_Line13 | EXTI_Line14 | EXTI_Line15,EXTI_Trigger_Falling);
   EnableButton_IRQ(EXTI15_10_IRQn);
}

void EnableButton_IRQ(uint8_t interupt_num){
	  /* Enable and set EXTI0 Interrupt to the lowest priority */
	  NVIC_InitStructure.NVIC_IRQChannel = interupt_num;
	  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
	  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
	  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	  NVIC_Init(&NVIC_InitStructure);
}

void DisableButton_IRQ(uint8_t interupt_num){
	  /* Enable and set EXTI0 Interrupt to the lowest priority */
	  NVIC_InitStructure.NVIC_IRQChannel = interupt_num;
	  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0F;
	  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0F;
	  NVIC_InitStructure.NVIC_IRQChannelCmd = DISABLE;
	  NVIC_Init(&NVIC_InitStructure);

}

void configure_EXTI(uint32_t exti_line,EXTITrigger_TypeDef edge_trigger) {
	EXTI_InitTypeDef   	EXTI_InitStructure;

	EXTI_InitStructure.EXTI_Line = exti_line;
	EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStructure.EXTI_Trigger = edge_trigger;
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure);
}
